package com.imon.sort;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;

/**
 * Hello world!
 * 
 */
public class App {
	public static void main(String[] args) throws IOException {
		new App().run();
	}

	private void run() {
		Collection<File> allFiles = getAllInputFiles(new File("."), "in");
		for (File aFile : allFiles) {
			processFile(aFile);
		}
	}

	private void processFile(File aFile) {
		System.out.println("Reading :" + aFile.getAbsolutePath());
		NumbersFileReader fileReader = new NumbersFileReader(aFile);

		SortedSet<Integer> sortedNumbers = new TreeSet<Integer>();
		for (String line : fileReader) {
			sortedNumbers.add(Integer.parseInt(line));
		}
		// save it in out*
		writeToFile(aFile, sortedNumbers);
	}

	private void writeToFile(File aFile, SortedSet<Integer> sortedNumbers) {
		try {
			String outputFilename = getOutputFilename(aFile.getName());
			File outputFile = new File(outputFilename);
			System.out.println("Writing:" + outputFile.getAbsolutePath());

			PrintWriter printWriter = new PrintWriter(new File(outputFilename));
			Iterator<Integer> iterator = sortedNumbers.iterator();
			while (iterator.hasNext()) {
				Integer number = iterator.next();
				printWriter.println(number);
			}
			printWriter.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	private String getOutputFilename(String name) {
		return name.replace("in", "out");
	}

	private Collection<File> getAllInputFiles(File directory, String pattern) {
		return FileUtils.listFiles(directory, FileFilterUtils.prefixFileFilter(pattern), null);
	}
}
